<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" size="small">
                <el-row>
                    <el-col :span=6>
                        <el-form-item label="评价来源" prop="source">
                            <el-select v-model="condition.search.source"
                                       placeholder="评价来源">
                                <el-option label="团购" value="团购"></el-option>
                                <el-option label="预订评价" value="预订评价"></el-option>
                                <el-option label="买单评价" value="买单评价"></el-option>
                                <el-option label="打开评价" value="打开评价"></el-option>
                                <el-option label="免费试评价" value="免费试评价"></el-option>
                                <el-option label="门店评价" value="门店评价"></el-option>
                                <el-option label="其它评价" value="其它评价"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="平台" prop="platform">
                            <el-select v-model="condition.search.platform"
                                       placeholder="平台">
                                <el-option label="点评" :value="1"></el-option>
                                <el-option label="美团" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="商家是否回复" prop="merchantReplyFlag">
                            <el-select v-model="condition.search.merchantReplyFlag"
                                       placeholder="商家是否回复">
                                <el-option label="是" :value="true"></el-option>
                                <el-option label="否" :value="false"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="打分" prop="accurateScore">
                            <el-select v-model="condition.search.accurateScore"
                                       placeholder="打分">
                                <el-option label="5.0" value="5.0"></el-option>
                                <el-option label="4.5" value="4.5"></el-option>
                                <el-option label="4.0" value="4.0"></el-option>
                                <el-option label="3.5" value="3.5"></el-option>
                                <el-option label="3.0" value="3.0"></el-option>
                                <el-option label="2.5" value="2.5"></el-option>
                                <el-option label="2.0" value="2.0"></el-option>
                                <el-option label="1.5" value="1.5"></el-option>
                                <el-option label="1.0" value="1.0"></el-option>
                                <el-option label="0.5" value="0.5"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span=6>
                        <el-form-item label="星级标签" prop="starTag">
                            <el-select v-model="condition.search.starTag"
                                       placeholder="星级标签">
                                <el-option label="好评(4.5-5.0)" value="GOOD"></el-option>
                                <el-option label="中评(4.0)" value="NORMAL"></el-option>
                                <el-option label="差评(0.5-3.5)" value="BAD"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="用户ID" prop="userId">
                            <el-input v-model="condition.search.userId"
                                      placeholder="用户ID"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="是否为VIP" prop="isVip">
                            <el-select v-model="condition.search.isVip"
                                       placeholder="是否为VIP">
                                <el-option label="是" :value="true"></el-option>
                                <el-option label="否" :value="false"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item>
                            <el-button type="primary" v-on:click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" v-on:click="reset">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" v-on:click="exportExcel">导出</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" v-on:click="showReplyTemplate">回复模版</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="danger" v-on:click="reSync">重新同步</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-table
            id="dpFeedbackTable"
            :data="tableData"
            size="small"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column
                prop="id"
                label="唯一ID">
            </el-table-column>
            <el-table-column
                prop="platform"
                :formatter="formatPlatform"
                label="平台">
            </el-table-column>
            <el-table-column
                prop="source"
                label="评价来源">
            </el-table-column>
            <el-table-column
                prop="content"
                width="280px"
                label="评价内容">
                <template v-slot="scope">
                    <table-popover :text=scope.row.content :length="2048"></table-popover>
                </template>
            </el-table-column>
            <el-table-column
                prop="accurateScore"
                label="打分">
            </el-table-column>
            <el-table-column
                prop="userName"
                label="用户名称">
                <template v-slot="scope">
                    <el-link @click="clickProfile(scope.row)">
                        {{ scope.row.userName }}
                    </el-link>
                </template>
            </el-table-column>
            <!--            <el-table-column-->
            <!--                prop="userAvatar"-->
            <!--                label="用户头像">-->
            <!--                <template v-slot="scope">-->
            <!--                    <el-image style="width: 40px; height: 40px"-->
            <!--                              :src="scope.row.userAvatar"-->
            <!--                              fit="contain">-->
            <!--                    </el-image>-->
            <!--                </template>-->
            <!--            </el-table-column>-->
            <el-table-column
                prop="isVip"
                :formatter="formatBoolean"
                label="是否为VIP">
            </el-table-column>
            <el-table-column
                prop="viewCount"
                label="浏览次数">
            </el-table-column>
            <el-table-column
                prop="merchantReplyFlag"
                :formatter="formatBoolean"
                label="是否回复">
            </el-table-column>
            <el-table-column
                prop="feedbackTime"
                label="评价时间">
            </el-table-column>
            <el-table-column
                prop="createTime"
                label="同步时间">
            </el-table-column>
            <el-table-column
                label="操作"
                fixed="right"
                width="80px">
                <template v-slot="scope">
                    <div>
                        <el-button @click="reply(scope.row)" type="text" size="small">回复</el-button>
                        <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            small
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="condition.page"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size.sync="condition.rows"
            layout="sizes, prev, pager, next"
            :total.sync="condition.total">
        </el-pagination>
        <el-dialog title="回复评价" width="50%" :visible.sync="replyDialogVisible">
            <el-form :model="replyForm" label-width="120px" size="small">
                <el-form-item label="评价内容">
                    <el-input v-model="replyForm.content" placeholder="评价内容" autosize :disabled="true"
                              type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="历史回复" v-if="replyForm.replyList.length > 0">
                    <el-table
                        size="small"
                        id="mainTable"
                        :data="replyForm.replyList"
                        header-cell-class-name="tableHeaderStyle"
                        :row-class-name="tableRowClassName">
                        <el-table-column prop="userName" label="用户昵称" width="80px"></el-table-column>
                        <el-table-column prop="replyTime" label="回复时间" width="80px"
                                         :formatter="formatTimestamp"></el-table-column>
                        <el-table-column prop="content" label="回复内容"></el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item label="图片信息" v-if="replyForm.pictures.length > 0">
                    <el-row v-for="item in replyForm.rowsData" :key="item.id" type="flex">
                        <el-col :span="4" v-for="col in item.cols" :key="item.id">
                            <el-image :src="col.url" fit="cover" class="pic"
                                      :preview-src-list="replyForm.imgUrls"></el-image>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item label="选择模版">
                    <el-select v-model="replyForm.replyTemplateContent" placeholder="选择模版"
                               @change="changeSelectTemplate" clearable>
                        <el-option-group
                            v-for="group in replyTemplatesGrouped"
                            :key="group.label"
                            :label="group.label">
                            <el-option
                                v-for="item in group.options"
                                :key="item.id"
                                :label="item.name"
                                :value="item.content">
                                {{ item.name }} | {{ item.content }}
                            </el-option>
                        </el-option-group>
                    </el-select>
                </el-form-item>
                <el-form-item label="回复内容">
                    <el-input v-model="replyForm.replyContent" placeholder="回复内容" :autosize="{ minRows: 2}"
                              type="textarea"></el-input>
                    <div class="form-tips">支持使用大写字母
                        <el-link type="primary" @click="clickN">N</el-link>
                        代替客户昵称，
                        <el-link type="primary" @click="clickM">M</el-link>
                        代替门店名称，回复会更加人性化～，最新上线：
                        <el-link type="danger" @click="clickAI">AI回复</el-link>
                        ，回复质量远远胜于人工回复！
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="replyDialogVisible = false" size="small">取 消</el-button>
                <el-button @click="replyConfirm" type="primary" size="small">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="评价模版" width="50%" :visible.sync="replyTemplateDialogVisible">
            <dp-feedback-reply-template :shop-id="shopId" category="MERCHANT"></dp-feedback-reply-template>
            <div slot="footer" class="dialog-footer">
                <el-button @click="replyTemplateDialogVisible = false" size="small">取 消</el-button>
                <el-button @click="replyTemplateDialogVisible = false" type="primary" size="small">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="同步数据" width="40%" :visible.sync="reSyncDialogVisible">
            <el-form :model="reSyncForm" label-width="120px" size="small">
                <el-form-item label="请选择同步日期">
                    <el-select v-model="reSyncForm.daysType" placeholder="请选择" clearable>
                        <el-option label="昨天" value="YESTERDAY"></el-option>
                        <el-option label="近三天" value="THREE"></el-option>
                        <el-option label="近七天" value="SEVEN"></el-option>
                        <el-option label="近十天" value="TEN"></el-option>
                        <el-option label="近30天" value="THIRTY"></el-option>
                        <el-option label="自定义" value="USER_DEFINE"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="请选择日期" v-if="reSyncForm.daysType === 'USER_DEFINE'">
                    <el-date-picker
                        v-model="reSyncForm.dateRange"
                        value-format="yyyy-MM-dd"
                        unlink-panels
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :picker-options="this.CONST.analysis_date_options">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="reSyncDialogVisible = false" size="small">取 消</el-button>
                <el-button @click="reSyncConfirm" type="primary" size="small" v-loading.fullscreen.lock="syncLoading">
                    确 定
                </el-button>
            </div>
        </el-dialog>

        <el-divider content-position="left">评价分析</el-divider>
        <dp-feedback-analysis :shop-id="shopId" :shop-name="shopName"></dp-feedback-analysis>
    </div>
</template>

<script>
import {
    addDpFeedback,
    deleteDpFeedback,
    generateReplyContentByChatGPT,
    getDpFeedbackByPage,
    getDpFeedbackReplyTemplatesByShopId,
    replyDpFeedback,
    reSyncDpShopFeedbackData,
    updateDpFeedback
} from '@/api/api'
import TablePopover from "@/component/single/TablePopover";
import DpFeedbackReplyTemplate from "@/component/DpFeedbackReplyTemplate";
import DpFeedbackAnalysis from "@/component/analysis/DpFeedbackAnalysis";
import {Loading} from 'element-ui';

export default {
    name: "DpFeedback",
    components: {TablePopover, DpFeedbackReplyTemplate, DpFeedbackAnalysis},
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 10,
                total: 0,
                search: {}
            },
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},

            replyDialogVisible: false,
            replyForm: {
                content: '',
                shopId: '',
                replyContent: '',
                replyList: [],
                pictures: [],
            },

            replyTemplateDialogVisible: false,

            // 回复模版列表
            replyTemplates: [],
            // 回复模版列表分组
            replyTemplatesGrouped: [],

            // 重新同步
            reSyncDialogVisible: false,
            reSyncForm: {
                daysType: null,
            },

            syncLoading: false,
        }
    },
    // 这里定义需要父组件传过来的东西
    props: {
        shopId: String,
        shopName: String,
        size: {
            type: String,
            default: 'small'
        },
    },
    methods: {
        reSync() {
            this.reSyncDialogVisible = true;
        },
        reSyncConfirm() {
            if (!this.reSyncForm.daysType) {
                this.$message({
                    type: 'error',
                    message: '请选择同步日期!'
                });
                return;
            }
            this.reSyncForm.shopId = this.shopId;
            if (this.reSyncForm.daysType === 'USER_DEFINE') {
                this.reSyncForm.startDate = this.reSyncForm.dateRange[0];
                this.reSyncForm.endDate = this.reSyncForm.dateRange[1];
            }
            this.syncLoading = true;
            reSyncDpShopFeedbackData(this.reSyncForm).then(data => {
                if (data.respCode == 1000) {
                    this.$message({
                        type: 'success',
                        message: '同步成功!'
                    });
                    this.getData();
                    this.reSyncDialogVisible = false;
                }
                this.syncLoading = false;
            })
        },
        changeSelectTemplate(value) {
            if (value) {
                // 替换占位符号
                this.replyForm.replyContent = value.replace('N', this.selectedRow.userName).replace('M', this.selectedRow.shopName);
            }
        },
        showReplyTemplate() {
            this.replyTemplateDialogVisible = true;
        },
        clickProfile(row) {
            let url = "https://m.dianping.com/userprofile/" + row.userId;
            window.open('javascript:window.name;', '<script>location.replace("' + url + '")<\/script>');
        },
        clickN() {
            this.replyForm.replyContent = this.replyForm.replyContent + this.selectedRow.userName;
        },
        clickM() {
            this.replyForm.replyContent = this.replyForm.replyContent + this.selectedRow.shopName;
        },
        clickAI() {
            let options = {fullscreen: true, background: 'rgba(0, 0, 0, 0.8)', text: '系统正在努力生成回复内容'};
            let loadingInstance = Loading.service(options);
            generateReplyContentByChatGPT({'id': this.selectedRow.id}).then(data => {
                loadingInstance.close();
                if (data.respCode == 1000) {
                    this.replyForm.replyContent = data.body;
                }
            })
        },
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            return '';
        },
        handleSizeChange(val) {
            this.getData();
        },
        handleCurrentChange(val) {
            this.getData();
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        // 格式平台
        formatPlatform: function (row, column, cellValue) {
            if (cellValue) {
                return "点评";
            } else {
                return "美团";
            }
        },
        formatTimestamp: function (row, column, cellValue) {
            return this.GLOBAL.timestampFormat(cellValue / 1000);
        },
        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '编辑';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#dpFeedbackTable', this.shopName + '评价数据.xlsx');
        },
        reply: function (row) {
            this.selectedRow = row;
            this.replyForm.id = row.id;
            this.replyForm.content = row.content;
            this.replyForm.shopId = row.shopId;
            this.replyForm.replyContent = "";
            this.replyForm.replyList = JSON.parse(row.replyList);
            this.replyForm.pictures = JSON.parse(row.pictures);
            this.replyForm.rowsData = this.GLOBAL.convertArray(this.replyForm.pictures, 6);
            this.replyForm.imgUrls = [];
            this.replyForm.pictures.forEach((item, index, arr) => {
                this.replyForm.imgUrls.push(item.url);
            })
            this.replyForm.replyTemplateContent = "";
            this.getTemplates();
            this.replyDialogVisible = true;
        },
        replyConfirm: function () {
            replyDpFeedback(this.replyForm).then(data => {
                if (data.respCode == 1000) {
                    this.$message({
                        type: 'success',
                        message: '回复成功～'
                    });
                    this.replyDialogVisible = false;
                    this.getData();
                }
            })
        },
        add: function () {
            addDpFeedback(this.addOrUpdateForm).then(data => {
                this.addOrUpdateDialogVisible = false;
                this.getData();
            });
        },
        update: function () {
            updateDpFeedback(this.addOrUpdateForm).then(data => {
                this.addOrUpdateDialogVisible = false;
                this.getData();
            });
        },
        onDelete: function (row) {
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteDpFeedback({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '编辑') {
                this.update();
            }
        },
        // 获取表格数据
        getData: function () {
            if (this.shopId) {
                this.condition.search.shopId = this.shopId;
            }
            getDpFeedbackByPage(this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
            });
        },
        getTemplates: function () {
            let param = {};
            if (this.shopId) {
                param.shopId = this.shopId;
            }
            getDpFeedbackReplyTemplatesByShopId(param).then(data => {
                this.replyTemplates = data.body;
                let options = []
                let good_options = [];
                let normal_options = [];
                let bad_options = [];
                this.replyTemplates.forEach((item, index, arr) => {
                    if (item.type == 'GOOD') {
                        good_options.push(item);
                    }
                    if (item.type == 'NORMAL') {
                        normal_options.push(item);
                    }
                    if (item.type == 'BAD') {
                        bad_options.push(item);
                    }
                })
                options.push({
                    label: '好评模版',
                    options: good_options,
                })
                options.push({
                    label: '中评模版',
                    options: normal_options,
                })
                options.push({
                    label: '差评模版',
                    options: bad_options,
                })
                this.replyTemplatesGrouped = options;
            });
        },
    },
    created() {
        this.getData();
    },
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}

.pic {
    width: 80px;
    height: 80px;
}
</style>
